/*
 * @Author: kuangxj
 * @Email: frankxjkuang@gmail.com
 * @Date: 2018-08-25 10:43:58
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-12-23 13:51:26
 * @Description: example api
 */

//先包含进来
var MongoDB = require("../../mongodb/mongodb");
// 错误回调
const error = async (ctx, err) => {
  console.log(err);
  ctx.status = 500;
  ctx.body = err;
};

// 查询所有数据
const getExample = async (ctx, next) => {
  // Promise 方式
  await MongoDB.find("example", {}, {})
    .then(res => {
      ctx.status = 200;
      ctx.body = {
        msg: "成功!!",
        data: res
      };
    })
    .catch(err => {
      error(ctx, err);
    });
  //
  return;
  // await 方式
  const res = await MongoDB.find("example", {}, {});
  ctx.status = 200;
  ctx.body = {
    msg: "成功!!",
    data: res
  };
};

// 查詢 单条数据
const getone = async (ctx, next) => {
  await MongoDB.findOne("example", ctx.query)
    .then(res => {
      ctx.status = 200;
      ctx.body = {
        msg: "成功!!",
        data: res
      };
    })
    .catch(err => {
      error(ctx, err);
    });
};
//插入数据
const postExample = async (ctx, next) => {
  const req = ctx.request.body;
  ctx.status = 200;
  console.log(req, "zhj11111111");
  if (!req.msg || typeof req.msg != "string") {
    ctx.status = 401;
    ctx.body = {
      msg: "post request!!",
      desc: `parameter error！！msg: ${req.msg}`,
      data: req
    };
    console.log(1);
    return;
  }

  await new Promise((reslove, reject) => {
    MongoDB.save("example", { msg: req.msg }, function(err, res) {
      if (err) {
        reject(err);
      } else {
        reslove(res);
      }
    });
  })
    .then(res => {
      ctx.body = {
        msg: "插入成功"
      };
    })
    .catch(err => {
      ctx.body = {
        msg: "插入失败" + err.msg
      };
    });
};

module.exports = {
  getone,
  getExample,
  postExample
};
